#!/usr/bin/env python
# coding: utf-8
import web
from controllers.weibo.weibo import APIClient
#from weibopy.auth import OAuthHandler
#from weibopy.api import API
import checkkey
from config import settings
from config.urls import urls
from controllers.utils import tfusers, logger
from controllers.sessionHandler import session_get, session_set 
from config.settings import _CALLBACK_URL 
logger = logger.logger()
render = settings.render
app = web.application( urls, globals() )


if web.config.get( '_session' ) is None:
#web.py中有三种session机制，本应用采用session保存在本地文件的机制
    session = web.session.Session( app, web.session.DiskStore( "sessions" ) )
    web.config._session = session
else:
    session = web.config._session

#首先从session中获取access_token，没有就转向新浪微博页面认证
#认证成功后将access_token保存在session中
class index:
    def GET( self ):
        access_token, uid, expires_in = session_get( session )
        logger.debug( "session.session_id-------->%s, %s" % ( session.session_id, access_token ) )
        print "session.session_id-------->%s, %s" % ( session.session_id, access_token ) 
        if  access_token is None:
            return render.login()
        else:
            try:
                client = APIClient( app_key = settings.CONSUME_KEY, app_secret = settings.CONSUME_SECRET )
                client.set_access_token( access_token, expires_in )
                key = checkkey.generatekey( session.session_id )   #生成动态可以用以验证
                user = tfusers.getUser( int( uid ) )
            except Exception, data:
                print 'Error---->>>>', data
            if user is None:
                raise web.found( client.get_authorize_url( _CALLBACK_URL ) )
            return render.index( uid, user, key )  #user is dict, not a object


class login:
    def GET( self ):
        client = APIClient( app_key = settings.CONSUME_KEY, app_secret = settings.CONSUME_SECRET )
        raise web.found( client.get_authorize_url( _CALLBACK_URL ) )


#页面回调，新浪微博验证成功后会返回本页面
class callBack:
    def GET( self ):
        ins = web.input()
        code = ins.get( 'code', None )
        print 'code:', code
        if code:
            try:
                client = APIClient( app_key = settings.CONSUME_KEY, app_secret = settings.CONSUME_SECRET )
                token = client.request_access_token( code, _CALLBACK_URL )
                client.set_access_token( token.access_token, token.expires_in )
                session_set( session, token.access_token, token.uid, token.expires_in )
                user = client.get.users__show( uid = token.uid )
                tfusers.updateUser( user ) # 用户授权登录后记录用户信息，记录失败不做强制条件，当需要用户信息时可再次记录
                #获取跳转过来的页面，然后跳转回去
                referer = web.ctx.env.get( 'HTTP_REFERER', '/' )
            except Exception, data:
                web.header( "Content-Type", "text/html;charset=utf-8" )
                logger.error( 'Exception:%s' % data )
                print 'Exception:', data
                return ':-( 出错了'
            print referer
            raise web.found( referer )


#退出微博，返回到首页
class Logout:
    def GET( self ):
        session_set( session, None, None, -1 )
        web.found( '/' )


if  __name__ == "__main__":
    app.run()
else:
    application = app.wsgifunc() 
